/*
 * ConfigFile.java
 *
 * Created on 05 May 2007, 20:00
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.cardcopier;

import com.wutka.jox.JOXBeanInputStream;
import com.wutka.jox.JOXBeanOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.log4j.Logger;

/**
 *
 * @author Mark
 */
public class ConfigFile {
    
    private static final Logger LOGGER = Logger.getLogger(ConfigFile.class);
    
    private static final String ROOT_ELEMENT_NAME = "applicationConfig";
    private final File configFile;
    
    public ConfigFile(File configFile) {
        this.configFile = configFile;
    }
    
    public ApplicationConfig readConfig() throws IOException {
        LOGGER.info("Reading application config from " + configFile.getAbsolutePath());
        ApplicationConfig applicationConfig;
        if (configFile.exists()) {
            JOXBeanInputStream joxIn = null;
            try {
                joxIn = new JOXBeanInputStream(new FileInputStream(configFile));
                applicationConfig = (ApplicationConfig) joxIn.readObject(ApplicationConfig.class);
            } finally {
                joxIn.close();
            }        
        } else {
            applicationConfig = new ApplicationConfig();
        }
        return applicationConfig;
    }
    
    public void writeConfig(ApplicationConfig config) throws IOException {
        LOGGER.info("Writing application config to " + configFile.getAbsolutePath());
        JOXBeanOutputStream joxOut = null;
        try {
            joxOut = new JOXBeanOutputStream(new FileOutputStream(configFile));
            joxOut.writeObject(ROOT_ELEMENT_NAME, config);
        } finally {
            joxOut.close();
        }
    }
}
